package com.project.sianet.data.HttpClient;


import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.project.sianet.R;
import com.project.sianet.data.Client.UsuarioClient;
import com.project.sianet.entidades.Usuario;
import com.project.sianet.util.SessionManager;
import com.project.sianet.util.Utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
//import android.util.Log;

public class UsuarioHttpClient implements UsuarioClient {

	private final Context context;
    private final HttpClient httpClient;
    
    public UsuarioHttpClient(Context context) {
    	
    	this.context = context;
        
        BasicHttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, false);
        httpClient = new DefaultHttpClient(params);
    	
    }
	
	@Override
	public Usuario validaToken(String login, String password) {
		
		Usuario result = null;
    	String content = get("Usuario_validaToken/" + login, login + password.toLowerCase(Locale.getDefault()));
    	//Log.d(LOG_TAG, "Result content:" + content);
    	
    	if (content != null) {
    		
    		try {
    			
    			if (content == "0") {
    				
    				result = new Usuario();
    				result.login = "ERROR";
    				result.nombres = context.getString(R.string.error_inesperado_URL);
    				
    			} else {
    			
	                JSONTokener tokener = new JSONTokener(content);
	                JSONObject obj = (JSONObject) tokener.nextValue();
	                String log = obj.isNull("Login") ? null : obj.getString("Login");
	//                String pwd = obj.getString("Password");
	                String pwd = null;
	                String nombres = obj.isNull("Nombres") ? null : obj.getString("Nombres");
	                String apepat = obj.isNull("ApellidoPaterno") ? null : obj.getString("ApellidoPaterno");
	                String apemat = obj.isNull("ApellidoMaterno") ? null : obj.getString("ApellidoMaterno");
	                String regId = obj.isNull("CodigoRegMovil") ? null : obj.getString("CodigoRegMovil");
	                int tipo = obj.getInt("Perfil");
	                Boolean acceso = obj.getBoolean("AccesoPermitido");
	
	                result = new Usuario(log, pwd, nombres, apepat, apemat, acceso, tipo, regId);
	                
    			}
                
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
    		
    	}
    	
        return result;
		
	}
	
	private String get(String path, String token) {
        try {
            HttpGet request = new HttpGet(getRequestURI(path));
            request.addHeader("Authorization", Utils.md5(token));
            HttpResponse res = httpClient.execute(request);
            String content = EntityUtils.toString(res.getEntity());
            return content;
        } catch (Exception e){
            Log.e("GET", "Se ha producido un error: " + e.toString() + "\nMensaje: " + e.getMessage());
            if (e.toString().contains("Host"))
            	return "0";
            else
            	return null;
        }
    }
	
	private String put(String path, String login, String oldregid, String regid, String accion) {
        try {
            HttpPut request;
            
            if (TextUtils.isEmpty(oldregid))
            	request = new HttpPut(getRequestURI(path + "/" + login.trim() + "/" + regid + "/" + accion));
            else
            	request = new HttpPut(getRequestURI(path + "/" + login.trim() + "/" + oldregid + "/" + regid + "/" + accion));
            
            HttpResponse res = httpClient.execute(request);
            String content = EntityUtils.toString(res.getEntity());
            return content;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private URI getRequestURI(String path) throws URISyntaxException {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//        String hostKey = context.getString(R.string.pref_host_key);
        String host = context.getString(R.string.pref_host_default) + prefs.getString("ColegioPF", "");
//        String host = prefs.getString(hostKey, context.getString(R.string.pref_host_default));
        //String portKey = context.getString(R.string.pref_port_key);
        //String port = prefs.getString(portKey, context.getString(R.string.pref_port_default));
        URI requestURI = new URI(host + "/MobileService.svc/" + path);
        //Log.i(LOG_TAG, "requestURI: " + requestURI);
        return requestURI;
    }
	
	@Override
	public void UpdateRegID(String login, String oldregid, String regid, String accion) {

    	try {
    		String content = put("Usuario_ActualizaRegId", login, oldregid, regid, accion);
    	} catch (Exception ex) {
    		ex.printStackTrace();
    	}
   
	}

}
